import store from '@/store'
import { isBlank } from '@/utils/validate'

// 全局公共方法
module.exports = vm => {
  // 检查登录状态
  const checkLogin = (e = {}) => {
    if (!store.getters['user/isLogin']) {
      uni.navigateTo({
        url: '/pages/user/login/login',
      })
      return false
    }
    return true
  }

  // 校验是否是H5页面
  const checkH5 = url => {
    const testHttp = uni.$u.test.url(url)
    if (testHttp) {
      return '/pages/h5/h5?url=' + url
    } else {
      return url
    }
  }
  // URL参数转对象
  const paramsToObj = url => {
    // 如果是完整URL，包含?号，先通过?号分解
    if (url.indexOf('?') != -1) {
      let arr = url.split('?')[1]
    }
    let arr = url.split('&') //先通过？分解得到？后面的所需字符串，再将其通过&分解开存放在数组里
    let obj = {}
    for (let i of arr) {
      obj[i.split('=')[0]] = i.split('=')[1] //对数组每项用=分解开，=前为对象属性名，=后为属性值
    }
    return obj
  }

  // 刷新当前页面
  const refreshPage = () => {
    const pages = getCurrentPages()
    const currentPage = pages[pages.length - 1]
    const url = '/' + currentPage.route + uni.$u.queryParams(currentPage.options)
    if (['pages/index/index', 'pages/user/index'].includes(currentPage.route)) uni.reLaunch({ url })
    else uni.redirectTo({ url })
  }

  // toast
  const showToast = (data = {}) => {
    if (typeof data == 'string') {
      uni.showToast({
        title: data,
        icon: 'none',
      })
    } else {
      uni.showToast({
        title: data.title,
        icon: data.icon || 'none',
        image: data.image || '',
        mask: data.mask || false,
        position: data.position || 'center',
        duration: data.duration || 1500,
        success: () => {
          setTimeout(() => {
            if (data.back) return uni.navigateBack()
            data.success && data.success()
          }, data.duration || 1500)
        },
      })
    }
  }

  // 单图上传
  const uploadImage = callback => {
    uni.chooseImage({
      count: 1,
      success: img => {
        const tempFilePaths = img.tempFilePaths
        uni.uploadFile({
          url: 'xxx.com',
          filePath: tempFilePaths[0],
          name: 'file',
          success: res => {
            callback && callback(JSON.parse(res.data))
          },
        })
      },
    })
  }

  uni.$u.func = {
    checkLogin,
    checkH5,
    paramsToObj,
    refreshPage,
    showToast,
    uploadImage,
  }
}
